// src/components/ProductDetailForm.tsx
import React, {useContext, useEffect, useState} from 'react';
import {Button, Col, Form, Input, InputNumber, message, Row, Select, Upload, type UploadFile} from 'antd';
import {DeleteOutlined, PlusOutlined, UploadOutlined} from '@ant-design/icons';
import ProductContext from '../context/ProductContext';
import {type Product} from '../api/service/ProductService';
import {fileService} from "../api/service/FileService.tsx";

const { Option } = Select;

interface ProductFormValues {
    title: string;
    description?: string;
    detailAddr?: string;
    coverAddr?: string;
    price: number;
    rate?: number;
    status: string;
    stockpile: number;
}

interface SpecificationItem {
    id?: number;
    item: string;
    value: string;
}

interface ProductDetailFormProps {
    product?: Product | null;
    coverUrl?: string;
    detailUrl?: string;
    onCancel?: () => void;
    onSuccess?: () => void;
}

const ProductDetailForm: React.FC<ProductDetailFormProps> = ({ product, coverUrl, detailUrl, onCancel, onSuccess }) => {
    const [form] = Form.useForm();
    const context = useContext(ProductContext);
    const [loading, setLoading] = useState(false);
    const [specifications, setSpecifications] = useState<SpecificationItem[]>([]);
    const [coverFileList, setCoverFileList] = useState<UploadFile[]>([]);
    const [detailFileList, setDetailFileList] = useState<UploadFile[]>([]);

    if (!context) {
        throw new Error('ProductDetailForm must be used within ProductProvider');
    }

    const { createProduct, updateProduct } = context;

    // 当 product 变化时，更新表单字段
    useEffect(() => {
        if (product) {
            form.setFieldsValue({
                title: product.title,
                description: product.description,
                detailAddr: product.detailAddr,
                coverAddr: product.coverAddr,
                price: product.price,
                rate: product.rate,
                status: product.status,
                stockpile: product.stockpile
            });

            // 设置规格数据
            if (product.specifications) {
                setSpecifications(product.specifications.map(spec => ({
                    id: spec.id,
                    item: spec.item,
                    value: spec.value
                })));
            }

            // 设置文件列表
            if (coverUrl) {
                setCoverFileList([{
                    uid: '-1',
                    name: 'cover.png',
                    status: 'done',
                    url: coverUrl,
                }]);
            } else if (product.coverAddr) {
                setCoverFileList([{
                    uid: '-1',
                    name: 'cover.png',
                    status: 'done',
                    url: product.coverAddr,
                }]);
            } else {
                setCoverFileList([]);
            }

            if (detailUrl) {
                setDetailFileList([{
                    uid: '-2',
                    name: 'detail.png',
                    status: 'done',
                    url: detailUrl,
                }]);
            } else if (product.detailAddr) {
                setDetailFileList([{
                    uid: '-2',
                    name: 'detail.png',
                    status: 'done',
                    url: product.detailAddr,
                }]);
            } else {
                setDetailFileList([]);
            }
        } else {
            form.resetFields();
            setSpecifications([]);
            setCoverFileList([]);
            setDetailFileList([]);
        }
    }, [product, coverUrl, detailUrl, form]);

    // 添加规格项
    const addSpecification = () => {
        setSpecifications([...specifications, { item: '', value: '' }]);
    };

    // 删除规格项
    const removeSpecification = (index: number) => {
        const newSpecifications = [...specifications];
        newSpecifications.splice(index, 1);
        setSpecifications(newSpecifications);
    };

    // 更新规格项
    const updateSpecification = (index: number, field: 'item' | 'value', value: string) => {
        const newSpecifications = [...specifications];
        newSpecifications[index] = {
            ...newSpecifications[index],
            [field]: value
        };
        setSpecifications(newSpecifications);
    };

    const onFinish = async (values: ProductFormValues) => {
        setLoading(true);
        try {
            // 处理封面图片上传
            let coverAddr = values.coverAddr;
            if (coverFileList.length > 0 && coverFileList[0].originFileObj) {
                coverAddr = await fileService.uploadFile(coverFileList[0].originFileObj, 'product-cover');
            }

            // 处理详情图片上传
            let detailAddr = values.detailAddr;
            if (detailFileList.length > 0 && detailFileList[0].originFileObj) {
                detailAddr = await fileService.uploadFile(detailFileList[0].originFileObj, "product-detail");
            }

            if (!product) {
                // 创建商品
                const success = await createProduct({
                    title: values.title,
                    description: values.description,
                    detailAddr: detailAddr,
                    coverAddr: coverAddr,
                    price: values.price.toString(), // 转换为字符串，与 GraphQL schema 一致
                    rate: values.rate?.toString(),
                    status: values.status,
                    stockpile: values.stockpile,
                    specifications: specifications.map(spec => ({
                        item: spec.item,
                        value: spec.value
                    }))
                });

                if (success) {
                    message.success('商品创建成功');
                    form.resetFields();
                    setSpecifications([]);
                    setCoverFileList([]);
                    setDetailFileList([]);
                    onSuccess?.();
                } else {
                    message.error('商品创建失败');
                }
            } else {

                // 处理封面图片上传
                let coverAddr = values.coverAddr;
                if (coverFileList.length > 0 && coverFileList[0].originFileObj) {
                    console.log("coverFileList[0].originFileObj", coverFileList[0].originFileObj)
                    coverAddr = await fileService.uploadFile(coverFileList[0].originFileObj, 'product-cover');
                }

                console.log("coverAddr", coverAddr)
                // 处理详情图片上传
                let detailAddr = values.detailAddr;
                if (detailFileList.length > 0 && detailFileList[0].originFileObj) {
                    console.log("detailFileList[0].originFileObj", detailFileList[0].originFileObj)
                    detailAddr = await fileService.uploadFile(detailFileList[0].originFileObj, "product-detail");
                }
                console.log("detailAddr", detailAddr)

                // 更新商品
                const success = await updateProduct(product.id, {
                    title: values.title,
                    description: values.description,
                    detailAddr: detailAddr,
                    coverAddr: coverAddr,
                    price: values.price.toString(), // 转换为字符串，与 GraphQL schema 一致
                    rate: values.rate?.toString(),
                    status: values.status,
                    stockpile: values.stockpile,
                    specifications: specifications.map(spec => ({
                        id:  spec.id !== undefined ? spec.id.toString() : undefined,
                        item: spec.item,
                        value: spec.value
                    }))
                });

                if (success) {
                    message.success('商品更新成功');
                    onSuccess?.();
                } else {
                    message.error('商品更新失败');
                }
            }
        } catch (error: unknown) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            console.error('商品操作失败:', error);
            message.error(errorMessage || '商品操作过程中发生错误');
        } finally {
            setLoading(false);
        }
    };

    return (
        <Form
            form={form}
            layout="vertical"
            onFinish={onFinish}
        >
            {/* 封面图片上传 */}
            <Form.Item
                label="封面图片"
                name="coverAddr"
            >
                <Upload
                    listType="picture"
                    maxCount={1}
                    fileList={coverFileList}
                    onChange={({ fileList }) => setCoverFileList(fileList)}
                    beforeUpload={() => false} // 阻止自动上传
                >
                    <Button icon={<UploadOutlined />}>上传封面图片</Button>
                </Upload>
            </Form.Item>

            {/* 详情图片上传 */}
            <Form.Item
                label="详情图片"
                name="detailAddr"
            >
                <Upload
                    listType="picture"
                    maxCount={1}
                    fileList={detailFileList}
                    onChange={({ fileList }) => setDetailFileList(fileList)}
                    beforeUpload={() => false} // 阻止自动上传
                >
                    <Button icon={<UploadOutlined />}>上传详情图片</Button>
                </Upload>
            </Form.Item>

            <Form.Item
                name="title"
                label="商品名称"
                rules={[{ required: true, message: '请输入商品名称' }]}
            >
                <Input placeholder="请输入商品名称" />
            </Form.Item>

            <Form.Item
                name="description"
                label="商品描述"
            >
                <Input.TextArea placeholder="请输入商品描述" rows={3} />
            </Form.Item>

            <Form.Item
                name="price"
                label="价格"
                rules={[{ required: true, message: '请输入价格' }]}
            >
                <InputNumber
                    style={{ width: '100%' }}
                    placeholder="请输入价格"
                    min={0.00}
                    step={0.01}
                    formatter={value => `¥ ${value}`}
                    precision={2} // 限制为2位小数
                />
            </Form.Item>

            <Form.Item
                name="stockpile"
                label="库存"
                rules={[{ required: true, message: '请输入库存数量' }]}
            >
                <InputNumber
                    style={{ width: '100%' }}
                    placeholder="请输入库存数量"
                    min={0}
                    step={1}
                />
            </Form.Item>

            <Form.Item
                name="rate"
                label="评分"
                rules={[{ required: true, message: '请输入评分' }]}
            >
                <InputNumber
                    style={{ width: '100%' }}
                    placeholder="请输入评分"
                    min={0.0}
                    max={10.0}
                    step={0.1}
                />
            </Form.Item>

            <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
            >
                <Select placeholder="请选择状态">
                    <Option value="active">在售</Option>
                    <Option value="inactive">下架</Option>
                </Select>
            </Form.Item>



            {/* 商品规格部分 */}
            <div style={{ marginBottom: 24 }}>
                <div style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    marginBottom: 16
                }}>
                    <h4 style={{ margin: 0 }}>商品规格</h4>
                    <Button
                        type="dashed"
                        onClick={addSpecification}
                        icon={<PlusOutlined />}
                    >
                        添加规格
                    </Button>
                </div>

                {specifications.map((spec, index) => (
                    <Row key={index} gutter={16} style={{ marginBottom: 12 }}>
                        <Col span={10}>
                            <Input
                                placeholder="规格名称"
                                value={spec.item}
                                onChange={e => updateSpecification(index, 'item', e.target.value)}
                            />
                        </Col>
                        <Col span={10}>
                            <Input
                                placeholder="规格值"
                                value={spec.value}
                                onChange={e => updateSpecification(index, 'value', e.target.value)}
                            />
                        </Col>
                        <Col span={4}>
                            <Button
                                danger
                                icon={<DeleteOutlined />}
                                onClick={() => removeSpecification(index)}
                            />
                        </Col>
                    </Row>
                ))}

                {specifications.length === 0 && (
                    <div style={{
                        textAlign: 'center',
                        padding: '20px',
                        background: '#fafafa',
                        borderRadius: '4px',
                        border: '1px dashed #d9d9d9'
                    }}>
                        <p style={{ color: '#999', margin: 0 }}>暂无规格信息</p>
                    </div>
                )}
            </div>

            <Form.Item>
                <Button type="primary" htmlType="submit" loading={loading}>
                    {product ? '更新商品' : '创建商品'}
                </Button>
                <Button
                    style={{ marginLeft: 8 }}
                    onClick={onCancel}
                >
                    取消
                </Button>
            </Form.Item>
        </Form>
    );
};

export default ProductDetailForm;
